package com.martin.lib_base.model

import android.os.Handler
import android.os.Looper
import android.os.Message
import kotlinx.coroutines.flow.MutableStateFlow

/**
 * @author：孟凡华
 * @date：2023/9/5
 * @desc：
 */
class CountdownModel(
    // 倒计时时间/S
    private val time: Int,
    // 间隔/S
    private val interval: Int = 1,
    // 倒计时回调/S
    private val onTick: (Int) -> Unit = {},
    // 倒计时结束回调
    private val onFinish: () -> Unit
) {
    // 当前时间
    val currentTime = MutableStateFlow(time)

    private val messageWhat = 0x100

    private val handler by lazy {
        object : Handler(Looper.getMainLooper()) {
            override fun handleMessage(msg: Message) {
                if (msg.what == messageWhat) {
                    if (currentTime.value > 0) {
                        currentTime.value = currentTime.value - interval
                        onTick(currentTime.value)
                        sendEmptyMessageDelayed(messageWhat, interval * 1000L)
                    } else {
                        onFinish()
                    }
                }
            }
        }
    }

    /**
     * 开始倒计时
     */
    fun start() {
        onTick(currentTime.value)
        handler.sendEmptyMessageDelayed(messageWhat, interval * 1000L)
    }

    /**
     * 暂停倒计时
     */
    fun pause() {
        handler.removeMessages(messageWhat)
    }

    /**
     * 取消倒计时
     */
    fun cancel() {
        pause()
        currentTime.value = time
    }

}